<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon">
          <User />
        </el-icon>
        用户管理
      </div>
      <div class="page-actions">
        <el-button type="danger" :disabled="selectedUsers.length === 0" @click="handleBatchDelete"
          v-if="userStore.hasPermission('user.delete')">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd" v-if="userStore.hasPermission('user.create')">
          <el-icon>
            <Plus />
          </el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 统计仪表盘 -->
      <div class="dashboard-stats">
        <div class="stat-card total-users">
          <div class="stat-background">
            <div class="stat-icon">
              <el-icon>
                <UserFilled />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.total }}</div>
              <div class="stat-label">总用户数</div>
              <div class="stat-trend positive">
                <el-icon>
                  <TrendCharts />
                </el-icon>
                <span>+12%</span>
              </div>
            </div>
          </div>
        </div>

        <div class="stat-card active-users">
          <div class="stat-background">
            <div class="stat-icon">
              <el-icon>
                <CircleCheck />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.active }}</div>
              <div class="stat-label">活跃用户</div>
              <div class="stat-trend positive">
                <el-icon>
                  <TrendCharts />
                </el-icon>
                <span>+8%</span>
              </div>
            </div>
          </div>
        </div>

        <div class="stat-card new-users">
          <div class="stat-background">
            <div class="stat-icon">
              <el-icon>
                <Calendar />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.newToday }}</div>
              <div class="stat-label">今日新增</div>
              <div class="stat-trend positive">
                <el-icon>
                  <TrendCharts />
                </el-icon>
                <span>+25%</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <div class="search-container">
          <div class="search-header">
            <div class="search-title">
              <el-icon class="search-icon">
                <Search />
              </el-icon>
              <span>用户筛选</span>
            </div>
            <div class="quick-filters">
              <span class="filter-label"
                style="margin-right: 12px; color: #888; font-size: 14px; vertical-align: middle;">账户状态：</span>
              <el-button :type="queryParams.isActive === null ? 'primary' : ''"
                @click="handleQuickFilter('isActive', null)" size="small" class="filter-btn">
                全部
              </el-button>
              <el-button :type="queryParams.isActive === true ? 'success' : ''"
                @click="handleQuickFilter('isActive', true)" size="small" class="filter-btn">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                启用
              </el-button>
              <el-button :type="queryParams.isActive === false ? 'danger' : ''"
                @click="handleQuickFilter('isActive', false)" size="small" class="filter-btn">
                <el-icon>
                  <CloseBold />
                </el-icon>
                禁用
              </el-button>
            </div>
          </div>

          <div class="search-form">
            <el-form :model="queryParams" inline class="search-inputs">
              <el-form-item>
                <el-autocomplete v-model="queryParams.username" :fetch-suggestions="getSuggestions"
                  placeholder="搜索用户名或邮箱" clearable class="search-input" prefix-icon="Search"
                  @select="handleSuggestionSelect" @input="handleSearchInput" :trigger-on-focus="false">
                  <template #default="{ item }">
                    <div class="suggestion-item">
                      <el-icon class="suggestion-icon">
                        <User v-if="item.type === 'username'" />
                        <Message v-else />
                      </el-icon>
                      <span class="suggestion-text">{{ item.value }}</span>
                      <el-tag size="small" class="suggestion-tag">{{ item.label }}</el-tag>
                    </div>
                  </template>
                </el-autocomplete>
              </el-form-item>
              <el-form-item>
                <el-select v-model="queryParams.roleId" placeholder="选择角色" clearable class="role-select"
                  multiple-limit="3" @change="handleRoleChange">
                  <el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName || role.name"
                    :value="role.id">
                    <span style="float: left">{{ role.roleName || role.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ roleUserCounts[role.id] || 0 }}人
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch" class="search-btn" :loading="loading">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset" class="reset-btn">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 搜索统计和快捷操作 -->
            <div v-if="searchResultStats.total > 0" class="search-results-info">
              <div class="results-stats">
                <el-tag type="info" size="small">
                  找到 {{ searchResultStats.total }} 个用户
                </el-tag>
                <el-tag v-if="searchResultStats.filtered" type="warning" size="small">
                  已筛选 {{ searchResultStats.filtered }} 个结果
                </el-tag>
              </div>
              <div class="search-actions">
                <!-- <el-button size="small" text @click="saveSearch">
                  <el-icon><Star /></el-icon>
                  保存搜索
                </el-button> -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户表格 -->
      <div class="table-container">
        <el-table v-loading="loading" :data="userList" border style="width: 100%"
          @selection-change="handleSelectionChange" :row-class-name="getRowClassName" @sort-change="handleSortChange">
          <el-table-column type="selection" width="55" />

          <el-table-column prop="username" label="用户信息" min-width="250" fixed="left">
            <template #default="{ row }">
              <div class="user-info-card">
                <div class="user-avatar-container">
                  <el-avatar :size="40" :src="row.avatar">
                    {{ row.username?.[0]?.toUpperCase() }}
                  </el-avatar>
                  <div class="online-status" :class="{ online: row.isOnline, offline: !row.isOnline }"></div>
                </div>
                <div class="user-details">
                  <div class="user-name">
                    <span>{{ row.username }}</span>
                    <span v-if="row.isVip" class="vip-badge">VIP</span>
                  </div>
                  <div class="user-nickname" v-if="row.nickName">
                    <el-tag size="small" type="info">{{ row.nickName }}</el-tag>
                  </div>
                  <div class="user-email">{{ row.email }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 单独的昵称列 -->
          <el-table-column prop="nickName" label="昵称" width="150">
            <template #default="{ row }">
              <span v-if="row.nickName" class="nickname-text">{{ row.nickName }}</span>
              <span v-else class="no-nickname">未设置</span>
            </template>
          </el-table-column>

          <el-table-column prop="email" label="邮箱" width="200">
            <template #default="{ row }">
              {{ row.email }}
            </template>
          </el-table-column>

          <el-table-column prop="roles" label="角色" width="150">
            <template #default="{ row }">
              <div class="role-tags">
                <el-tag v-for="role in row.roles" :key="role.id" :type="getRoleTagType(role.roleCode)" size="small">
                  {{ role.roleName }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="isActive" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'" size="small" effect="plain">
                {{ row.isActive ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="loginCount" label="登录次数" width="100" sortable />

          <el-table-column prop="lastLoginAt" label="最后登录" width="160" sortable>
            <template #default="{ row }">
              {{ formatDate(row.lastLoginAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-tooltip content="查看详情">
                  <el-button type="primary" size="small" circle @click="handleView(row)">
                    <el-icon>
                      <View />
                    </el-icon>
                  </el-button>
                </el-tooltip>

                <el-tooltip content="编辑用户">
                  <el-button type="success" size="small" circle @click="handleEdit(row)"
                    v-if="userStore.hasPermission('user.update')">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                </el-tooltip>

                <el-tooltip content="角色分配">
                  <el-button type="warning" size="small" circle @click="handleAssignRole(row)"
                    v-if="userStore.hasPermission('user.assign')">
                    <el-icon>
                      <Key />
                    </el-icon>
                  </el-button>
                </el-tooltip>

                <el-tooltip content="删除用户">
                  <el-button type="danger" size="small" circle @click="handleDelete(row)"
                    v-if="userStore.hasPermission('user.delete')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <div class="pagination-info">
          <span>共 {{ total }} 条记录，已选择 {{ selectedUsers.length }} 条</span>
        </div>
        <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSearch"
          @current-change="handleSearch" />
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <UserForm v-model:visible="formVisible" :user="currentUser" @confirm="handleFormConfirm" />

    <!-- 用户详情对话框 -->
    <UserDetail v-model:visible="detailVisible" :user="currentUser" @edit="handleDetailEdit" />

    <!-- 角色分配对话框 -->
    <RoleAssignment v-model:visible="roleAssignVisible" :user="currentUser" @confirm="handleRoleAssignConfirm" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Delete, Search, Refresh, User, UserFilled, CircleCheck,
  Connection, TrendCharts, More,
  CloseBold, Calendar, View, Edit, Key, Lock, Clock, ChatLineRound,
  Message, Close, Star
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import UserForm from './UserForm.vue'
import UserDetail from './UserDetail.vue'
import RoleAssignment from './RoleAssignment.vue'

const userStore = useUserStore()

const loading = ref(false)
const userList = ref([])
const total = ref(0)
const selectedUsers = ref([])
const formVisible = ref(false)
const detailVisible = ref(false)
const roleAssignVisible = ref(false)
const currentUser = ref(null)
const showAdvancedSearch = ref(false)
const searchHistory = ref([])

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  username: '',
  email: '',
  isActive: null,
  isOnline: null,
  dateRange: null,
  minLoginCount: null,
  maxLoginCount: null,
  statusList: []
})

// 角色选项 - 从真实API获取
const roleOptions = ref([])
const roleUserCounts = ref({}) // 角色对应的用户数量

// 加载角色选项
const loadRoleOptions = async () => {
  try {
    const { roleApi } = await import('@/api/role')
    const response = await roleApi.getRoles()

    if (response.data && Array.isArray(response.data)) {
      roleOptions.value = response.data.map(role => ({
        id: role.id,
        name: role.roleName, // 后端字段是roleName
        code: role.roleCode || role.roleName // 后端字段是roleCode
      }))

      // 同时加载角色用户统计
      await loadRoleUserCounts()
    } else {
      roleOptions.value = []
    }
  } catch (error) {
    console.error('加载角色选项失败:', error)
    ElMessage.error('加载角色选项失败')
    roleOptions.value = []
  }
}

// 加载角色用户统计
const loadRoleUserCounts = async () => {
  try {
    // 调用角色API获取包含用户数量的角色数据
    const { roleApi } = await import('@/api/role')
    const res = await roleApi.getRoles()
    const counts = {}
    if (res.data && Array.isArray(res.data)) {
      res.data.forEach(role => {
        counts[role.id] = role.userCount || 0
      })
    }
    roleUserCounts.value = counts
  } catch (error) {
    console.error('加载角色用户统计失败:', error)
    // 如果API失败，设置默认值为0
    const counts = {}
    roleOptions.value.forEach(role => {
      counts[role.id] = 0
    })
    roleUserCounts.value = counts
  }
}

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const today = new Date()
      return [today, today]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近3个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 统计数据 - 从后端获取全局统计
const stats = ref({
  total: 0,
  active: 0,
  newToday: 0
})

// 加载用户统计信息
const loadUserStats = async () => {
  try {
    const response = await userApi.getUserStats()
    if (response && response.success) {
      stats.value = {
        total: response.data.total || 0,
        active: response.data.active || 0,
        newToday: response.data.newToday || 0
      }
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    // 如果获取统计失败，使用当前列表数据计算
    stats.value = {
      total: userList.value.length,
      active: userList.value.filter(user => user.isActive === true).length,
      newToday: userList.value.filter(user => {
        const today = new Date().toDateString()
        return new Date(user.createdAt).toDateString() === today
      }).length
    }
  }
}

// 搜索结果统计
const searchResultStats = computed(() => {
  const hasFilter = queryParams.username || queryParams.roleId || queryParams.dateRange || queryParams.status !== null || queryParams.isOnline !== null
  return {
    total: userList.value.length,
    filtered: hasFilter ? userList.value.length : 0
  }
})

// 已移除模拟数据，现在直接从后端API获取真实数据

// 快捷筛选方法
const handleQuickFilter = (key, value) => {
  queryParams[key] = value
  if (key === 'isOnline') {
    queryParams.isActive = null // 清除状态筛选
  }
  handleSearch()
}

// 获取搜索建议 - 从后端获取
const getSuggestions = async (queryString, cb) => {
  if (!queryString) {
    cb([])
    return
  }

  try {
    // 从后端搜索用户获取建议
    const response = await userApi.searchUsers({
      keyword: queryString,
      pageSize: 10
    })

    const suggestions = []
    response.data?.forEach(user => {
      suggestions.push({
        value: user.username,
        label: '用户名',
        type: 'username'
      })
      if (user.email) {
        suggestions.push({
          value: user.email,
          label: '邮箱',
          type: 'email'
        })
      }
    })

    cb(suggestions.slice(0, 10)) // 限制建议数量
  } catch (error) {
    console.error('获取搜索建议失败:', error)
    cb([])
  }
}

// 处理建议选择
const handleSuggestionSelect = (item) => {
  queryParams.username = item.value
  handleSearch()
}

// 处理搜索输入
const handleSearchInput = (value) => {
  // 实时搜索（防抖）
  clearTimeout(window.searchTimer)
  window.searchTimer = setTimeout(() => {
    if (value.length >= 2) {
      handleSearch()
    } else if (value.length === 0) {
      handleSearch()
    }
  }, 500)
}

// 角色变化处理
const handleRoleChange = () => {
  handleSearch()
}

// 日期变化处理
const handleDateChange = () => {
  handleSearch()
}

// 切换高级搜索
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 清除搜索
const clearSearch = () => {
  handleReset()
}

// 保存搜索
const saveSearch = () => {
  if (queryParams.username && !searchHistory.value.includes(queryParams.username)) {
    searchHistory.value.unshift(queryParams.username)
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    localStorage.setItem('userSearchHistory', JSON.stringify(searchHistory.value))
  }
  ElMessage.success('搜索条件已保存')
}

// 获取角色对应的用户数量 - 从后端获取统计
const getUserCountByRole = async (roleId) => {
  try {
    const response = await userApi.getUserStats()
    return response.data?.roleStats?.[roleId] || 0
  } catch (error) {
    console.error('获取角色用户统计失败:', error)
    return 0
  }
}

// 已移除模拟数据加载方法，现在统一使用loadUsers从后端获取数据

// 加载用户数据 - 从后端API获取
const loadUsers = async () => {
  try {
    loading.value = true

    // 检查登录状态
    const currentToken = userStore.token || localStorage.getItem('token')
    if (!currentToken) {
      ElMessage.error('请先登录再访问用户管理页面')
      userList.value = []
      total.value = 0
      loading.value = false
      return
    }

    // 构建筛选参数
    const filterParams = {}
    if (queryParams.username) filterParams.username = queryParams.username
    if (queryParams.email) filterParams.email = queryParams.email
    if (queryParams.roleId) filterParams.roleId = queryParams.roleId
    if (queryParams.isActive !== null && queryParams.isActive !== undefined) filterParams.isActive = queryParams.isActive

    // 处理日期范围
    if (queryParams.dateRange && queryParams.dateRange.length === 2) {
      filterParams.startDate = queryParams.dateRange[0].toISOString().split('T')[0]
      filterParams.endDate = queryParams.dateRange[1].toISOString().split('T')[0]
    }

    // 调用后端分页API获取用户数据 - pageIndex从0开始
    const response = await userApi.getUsersPaged(
      queryParams.page - 1, // 前端页码从1开始，后端从0开始
      queryParams.pageSize,
      filterParams
    )

    console.log('✅ 用户数据加载成功:', response)

    // 处理后端返回的数据结构
    if (response && response.code === 200 && response.isSuccess) {
      const data = response.data

      // 后端返回的数据结构: { Users: [], TotalCount: number, PageIndex: number, PageSize: number, TotalPages: number }
      userList.value = (data.Users || data.users || []).map(user => ({
        ...user,
        // 确保前端需要的字段存在
        isActive: user.isActive !== undefined ? user.isActive : true,
        isOnline: user.isOnline || false,
        isVip: user.isVip || false,
        roles: user.roles || [],
        loginCount: user.loginCount || 0,
        lastLoginAt: user.lastLoginAt || user.lastLoginTime,
        avatar: user.avatar || ''
      }))

      total.value = data.TotalCount || data.totalCount || 0

      console.log(`✅ 成功加载 ${userList.value.length} 条用户数据，总计 ${total.value} 条`)

      // 保存搜索历史
      if (queryParams.username) {
        saveSearchToHistory(queryParams.username)
      }

      // 只在有数据时显示成功消息，避免频繁弹窗
      if (userList.value.length > 0) {
        console.log(`✅ 用户数据加载完成: ${userList.value.length}/${total.value}`)
      }

      // 更新统计数据
      stats.value.total = total.value
      stats.value.active = userList.value.filter(user => user.isActive === true).length

    } else {
      console.warn('后端返回数据格式异常:', response)
      userList.value = []
      total.value = 0
      ElMessage.warning(response?.message || '暂无用户数据')
    }

  } catch (error) {
    console.error('❌ 加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败: ' + (error.message || '网络错误'))
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 保存搜索历史
const saveSearchToHistory = (searchText) => {
  if (searchText && !searchHistory.value.includes(searchText)) {
    searchHistory.value.unshift(searchText)
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    localStorage.setItem('userSearchHistory', JSON.stringify(searchHistory.value))
  }
}

// 重置搜索
const resetSearch = () => {
  queryParams.username = ''
  queryParams.roleId = null
  queryParams.status = null
  queryParams.isOnline = null
  queryParams.dateRange = []
  queryParams.minLoginCount = null
  queryParams.maxLoginCount = null
  queryParams.statusList = []

  loadUsers()
  ElMessage.success('搜索条件已重置')
}

// 清除搜索历史
const clearSearchHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('userSearchHistory')
  ElMessage.success('搜索历史已清除')
}

// 处理分页变化
const handlePageChange = (page) => {
  queryParams.pageNum = page
  loadUsers()
}

// 处理页面大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  loadUsers()
}

// 搜索
const handleSearch = () => {
  loadUsers()
}

// 重置搜索
const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    username: '',
    email: '',
    roleId: null,
    status: null,
    isOnline: null,
    dateRange: null
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 获取行类名
const getRowClassName = ({ row }) => {
  if (!row.status) return 'user-disabled'
  if (row.isVip) return 'user-vip'
  if (row.isOnline) return 'user-online'
  return ''
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  console.log('排序变化:', prop, order)
}

// 获取角色标签类型
const getRoleTagType = (code) => {
  const typeMap = {
    super_admin: 'danger',
    admin: 'warning',
    user: 'primary',
    guest: 'info'
  }
  return typeMap[code] || 'default'
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.success(`用户状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    row.status = !row.status // 恢复原状态
    ElMessage.error('状态更新失败')
  }
}

// 新增用户
const handleAdd = () => {
  currentUser.value = null
  formVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  currentUser.value = { ...row }
  formVisible.value = true
}

// 查看详情
const handleView = (row) => {
  currentUser.value = row
  detailVisible.value = true
}

// 角色分配
const handleAssignRole = (row) => {
  console.log('打开角色分配对话框，用户数据:', row)
  console.log('用户角色数据:', row.roles)
  currentUser.value = row
  roleAssignVisible.value = true
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    )

    // 只传递id数组
    const idList = selectedUsers.value.map(u => u.id)
    console.log('开始批量删除用户，ID列表：', idList)
    // 调用真实API，确保Content-Type为application/json
    await userApi.batchDeleteUsers(idList)
    console.log('批量删除API调用成功')
    ElMessage.success('批量删除成功')

    // 清空选择
    selectedUsers.value = []

    // 刷新列表
    handleSearch()
  } catch (error) {
    console.error('批量删除失败：', error)
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    }
  }
}

// 批量导出
// 下拉菜单命令处理
const handleDropdownCommand = (command, row) => {
  switch (command) {
    case 'resetPassword':
      handleResetPassword(row)
      break
    case 'loginHistory':
      handleLoginHistory(row)
      break
    case 'sendMessage':
      handleSendMessage(row)
      break
    case 'export':
      handleExportUser(row)
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户"${row.username}"的密码吗？`,
      '确认重置',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    )

    // 调用API重置密码
    await userApi.resetPassword(row.id)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败: ' + (error.response?.data?.message || error.message || '未知错误'))
    }
  }
}

// 登录历史
const handleLoginHistory = (row) => {
  ElMessage.info(`查看用户"${row.username}"的登录历史`)
}

// 发送消息
const handleSendMessage = (row) => {
  ElMessage.info(`向用户"${row.username}"发送消息`)
}

// 导出用户
const handleExportUser = (row) => {
  ElMessage.info(`导出用户"${row.username}"的数据`)
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.username}"吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    )

    console.log('删除用户:', row.id, row.username)

    // 调用删除API
    const result = await userApi.deleteUser(row.id)
    console.log('删除API结果:', result)

    ElMessage.success('用户删除成功')
    await handleSearch() // 刷新用户列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error(`用户删除失败: ${error.message || '未知错误'}`)
    }
  }
}

// 表单确认
const handleFormConfirm = async (formData) => {
  try {
    if (currentUser.value?.id) {
      // 编辑用户
      const updateData = {
        id: currentUser.value.id,
        username: formData.username,
        nickName: formData.nickName || formData.username,
        email: formData.email,
        isActive: formData.isActive,
        description: formData.description || null,
        avatar: formData.avatar || null
      }

      console.log('保存用户数据:', updateData)
      console.log('用户ID:', currentUser.value.id)
      const result = await userApi.updateUser(currentUser.value.id, updateData)
      console.log('保存结果:', result)
      ElMessage.success('用户信息更新成功')
    } else {
      // 新增用户
      const createData = {
        NickName: formData.nickName || formData.username,
        Username: formData.username,
        PlainPassword: formData.password,
        Email: formData.email,
        Avatar: formData.avatar || null,
        Description: formData.description || null
      }
      console.log('新增用户参数:', createData)
      await userApi.createUser(createData)
      ElMessage.success('用户创建成功')
    }

    formVisible.value = false
    console.log('开始刷新用户列表...')
    await handleSearch()
    console.log('用户列表刷新完成')
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error(error.message || '保存失败，请稍后重试')
  }
}

// 详情编辑
const handleDetailEdit = (user) => {
  detailVisible.value = false
  currentUser.value = user
  formVisible.value = true
}

// 角色分配确认
const handleRoleAssignConfirm = async (data) => {
  try {
    console.log('角色分配数据:', data)

    if (!data.userId || !Array.isArray(data.roleIds)) {
      ElMessage.error('角色分配数据格式错误')
      return
    }

    // 获取用户当前角色
    const currentUser = userList.value.find(user => user.id === data.userId)
    if (!currentUser) {
      ElMessage.error('用户不存在')
      return
    }

    // 获取用户当前角色ID列表
    const currentRoleIds = (currentUser.roles || []).map(role => role.id)
    const newRoleIds = data.roleIds

    // 找出需要添加的角色
    const rolesToAdd = newRoleIds.filter(roleId => !currentRoleIds.includes(roleId))

    // 找出需要移除的角色
    const rolesToRemove = currentRoleIds.filter(roleId => !newRoleIds.includes(roleId))

    console.log('需要添加的角色:', rolesToAdd)
    console.log('需要移除的角色:', rolesToRemove)

    // 执行角色移除
    for (const roleId of rolesToRemove) {
      try {
        await userApi.removeRole(data.userId, roleId)
        console.log('成功移除角色:', roleId)
      } catch (error) {
        console.error('移除角色失败:', roleId, error)
        ElMessage.error(`移除角色失败: ${error.message}`)
      }
    }

    // 执行角色添加
    for (const roleId of rolesToAdd) {
      try {
        await userApi.assignRole(data.userId, roleId)
        console.log('成功添加角色:', roleId)
      } catch (error) {
        console.error('添加角色失败:', roleId, error)
        ElMessage.error(`添加角色失败: ${error.message}`)
      }
    }

    ElMessage.success('角色分配更新成功')
    roleAssignVisible.value = false
    await handleSearch() // 刷新用户列表

  } catch (error) {
    console.error('角色分配失败:', error)
    ElMessage.error('角色分配失败')
  }
}

onMounted(() => {
  loadUserStats() // 加载统计数据
  loadUsers()     // 加载用户列表
  loadRoleOptions() // 加载角色选项
})
</script>

<style scoped>
.page-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  padding: 0;
  margin: 0;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  color: white;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 28px;
  font-weight: 700;
  color: white;
}

.title-icon {
  font-size: 32px;
  color: rgba(255, 255, 255, 0.9);
}

.page-actions {
  display: flex;
}

.title-icon {
  font-size: 32px;
  color: rgba(255, 255, 255, 0.9);
}

.page-actions {
  display: flex;
  gap: 12px;
}

.page-actions .el-button {
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.page-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.page-content {
  padding: 32px;
  background: white;
  margin: 0;
  min-height: calc(100vh - 120px);
}

/* 统计仪表盘样式 */
.dashboard-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  border-radius: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.stat-background {
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  position: relative;
}

.total-users .stat-background {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.active-users .stat-background {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.new-users .stat-background {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  font-size: 28px;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 36px;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 12px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  opacity: 0.8;
}

.stat-trend.positive {
  color: rgba(255, 255, 255, 0.9);
}

/* 搜索区域样式 */
.search-section {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 32px;
  overflow: hidden;
}

.search-container {
  padding: 24px;
}

.search-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.search-icon {
  color: #6366f1;
}

.quick-filters {
  display: flex;
  gap: 8px;
}

.filter-btn {
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.filter-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  border-top: 1px solid #f3f4f6;
  padding-top: 24px;
}

.search-inputs {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.role-select {
  width: 160px;
}

.date-picker {
  width: 260px;
}

.search-btn,
.reset-btn {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.search-btn:hover,
.reset-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格容器样式 */
.table-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 24px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 0;
  border: none;
}

:deep(.el-table th) {
  background: #f8fafc;
  color: #374151;
  font-weight: 600;
  border-bottom: 2px solid #e5e7eb;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f3f4f6;
  padding: 16px 12px;
}

:deep(.el-table tr:hover) {
  background: #f8fafc;
}

/* 用户信息卡片样式 */
.user-info-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.user-avatar-container {
  position: relative;
}

.user-details {
  flex: 1;
}

.user-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.user-email {
  color: #6b7280;
  font-size: 13px;
}

.vip-badge {
  background: linear-gradient(135deg, #f59e0b, #d97706);
  color: white;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 600;
}

.online-status {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
}

.online-status.online {
  background: #10b981;
}

.online-status.offline {
  background: #6b7280;
}

/* 角色标签样式 */
.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-buttons .el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.pagination-info {
  color: #6b7280;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .dashboard-stats {
    grid-template-columns: 1fr;
  }

  .search-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .quick-filters {
    justify-content: center;
  }

  .search-inputs {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input,
  .role-select,
  .date-picker {
    width: 100%;
  }

  .pagination {
    flex-direction: column;
    gap: 16px;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: fadeInUp 0.6s ease forwards;
}

.stat-card:nth-child(1) {
  animation-delay: 0.1s;
}

.stat-card:nth-child(2) {
  animation-delay: 0.2s;
}

.stat-card:nth-child(3) {
  animation-delay: 0.3s;
}

.stat-card:nth-child(4) {
  animation-delay: 0.4s;
}

/* 滚动条美化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
  height: 8px;

  /* 昵称相关样式 */
  .user-nickname {
    margin-top: 2px;
  }

  .nickname-text {
    color: #606266;
    font-size: 13px;
  }

  .no-nickname {
    color: #c0c4cc;
    font-size: 12px;
    font-style: italic;
  }
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格固定列阴影 */
:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__fixed) {
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.custom-status-tag {
  display: inline-block;
  min-width: 48px;
  padding: 4px 14px;
  font-size: 14px;
  font-weight: bold;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  text-align: center;
  letter-spacing: 2px;
  transition: all 0.2s;
}

.custom-status-tag {
  display: inline-block;
  min-width: 60px;
  padding: 6px 18px;
  font-size: 15px;
  font-weight: bold;
  border-radius: 8px;
  text-align: center;
  letter-spacing: 2px;
  border: 2px solid transparent;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.2s;
}
.custom-status-tag.active {
  background: #e8f9f1;
  color: #21b97a;
  border-color: #21b97a;
}
.custom-status-tag.inactive {
  background: #fff0f0;
  color: #e74c3c;
  border-color: #e74c3c;
}
</style>